package com.kgc.web;

import com.kgc.dao.UserPaymentDao;
import com.kgc.entity.UserPayment;
import com.kgc.untils.PageUtils;
import com.kgc.vo.R;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "UserPaymentServlet", value = "/UserPaymentServlet")
public class UserPaymentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        UserPaymentDao userPaymentDao = new UserPaymentDao();
        String opt = request.getParameter("opt");  //获取标记
        if ("list".equals(opt)) {
            String name = request.getParameter("name");//查询词
            String page = request.getParameter("page");//获取页码
            String limit = request.getParameter("limit");//每页显示条数
            PageUtils pageUtils = new PageUtils();
            if (StringUtils.isNotEmpty(page)) {
                pageUtils.setCurrPageNo(Integer.parseInt(page));
            }
            if (StringUtils.isNotEmpty(limit)) {
                pageUtils.setPageSize(Integer.parseInt(limit));
            }
            int totalCount = userPaymentDao.countAll(name);
            pageUtils.init(totalCount);
            //查询数据
            List<UserPayment> list = userPaymentDao.selectAll(pageUtils, name);
            response.getWriter().write(R.success("用户列表加载成功...", totalCount, list).toJSON());

        } else if ("confirm".equals(opt)) {
            String id = request.getParameter("id");
            int count = userPaymentDao.updateStatus(Integer.parseInt(id));
            if (count > 0) {
                response.getWriter().write(R.success("缴费成功!").toJSON());
            } else {
                response.getWriter().write(R.error("缴费失败").toJSON());
            }
        }else if ("addPayment".equals(opt)){
            String value = request.getParameter("value");
            int userId = Integer.parseInt(request.getParameter("userId"));
            int paymentId = Integer.parseInt(request.getParameter("paymentId"));
            int count = userPaymentDao.addUserPayment(new UserPayment(userId, paymentId, value, null, 0));
            if (count > 0) {
                response.getWriter().write(R.success("添加缴费成功!").toJSON());
            } else {
                response.getWriter().write(R.error("添加缴费失败").toJSON());
            }


        }


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
